(function() {
    "use strict";

    if(typeof(console) == "null" || typeof(console) == "undefined") {
        console = {log: function(s) {alert(s);}};
    }

    var namespace = function(name, scope) {
        var a = name.split(".");
        var p = (scope || window);

        for(var i = 0; i < a.length; i++) {
            var n = a[i];

            if(typeof(p[n]) == "undefined") {
                p[n] = {};
            }
            p = p[n];
        }
        return p;
    };

    namespace("com.skin.upload");
    com.skin.util.namespace = namespace;

    var e = com.skin.upload.FileUpload = function(settings) {
        this.settings = settings;
    };

    e.prototype = {
        open: function() {
            var self = this;
            var settings = this.settings;
            var inputId = "_fileupload_" + (new Date()).getTime();
            var input = this.getFileInput(inputId, inputId, settings.accept, settings.multiple);
            var onchange = function(event) {
                var e = (event || window.event);
                var input = e.target;
                var files = input.files;

                if(files == null || files.length < 1) {
                    input.parentNode.parentNode.removeNode(input.parentNode);
                    return;
                }
                self.select(input.files);
            };
            this.addEventListener(input, "change", onchange);
            input.click();
        },
        select: function(files) {
            if(this.settings.select != null) {
                this.settings.select.apply(this, [files]);
            }
        },
        upload: function(url, name, file, data) {
            var self = this;
            var settings = this.settings;
            var xmlHttpRequest = this.getXmlHttpRequest();

            if(xmlHttpRequest == null || xmlHttpRequest == undefined) {
                if(settings.error != null) {
                    settings.error(null);
                }
                return;
            }

            var headers = settings.headers;
            var data = this.getFormData(name, file, data);
            xmlHttpRequest.open("post", url, true);

            xmlHttpRequest.onreadystatechange = function() {
                if(xmlHttpRequest.readyState == 4) {
                    if(xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200) {
                        if(settings.success != null) {
                            var result = self.getResponse(xmlHttpRequest.responseText, settings.dataType);
                            settings.success(result);
                        }
                    }
                    else {
                        if(settings.error != null) {
                            settings.error(xmlHttpRequest);
                        }
                    }
                }
            };

            xmlHttpRequest.ontimeout = settings.ontimeout;
            xmlHttpRequest.onprogress = settings.onprogress;
            xmlHttpRequest.upload.onprogress = settings.onuploadprogress;

            if(headers != null) {
                for(var i = 0; i < headers.length; i++) {
                    var header = headers[i];
                    xmlHttpRequest.setRequestHeader(header.name, header.value);
                }
            }
            xmlHttpRequest.send(data);
            return xmlHttpRequest;
        },
        addEventListener: function(target, type, handler) {
            if(target == null) {
                return;
            }

            if(target.attachEvent) {
                target.attachEvent("on" + type, handler);
            }
            else if(target.addEventListener) {
                target.addEventListener(type, handler, false);
            }
            else {
                target["on" + type] = handler;
            }
        },
        getFileInput: function(id, name, accept, multiple) {
            var params = {
                "id": id,
                "name": name,
                "type": "file",
                "accept": (accept || "*"),
                "multiple": multiple
            };

            var div = this.createElement("div");
            var input = this.createElement("input", params);
            div.style.display = "none";
            div.appendChild(input);
            document.body.appendChild(div);
            return input;
        },
        createElement: function(name, params) {
            var e = null;

            if(window.ActiveXObject) {
                e = document.createElement("<" + name + ">");
            }
            else {
                e = document.createElement(name);
            }

            if(params != null) {
                for(var i in params) {
                    if(params[i] != null) {
                        e.setAttribute(i, params[i]);
                    }
                }
            }
            return e;
        },
        getXmlHttpRequest: function() {
            var xmlHttpRequest = null;

            if(window.ActiveXObject != null) {
                xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            else {
                xmlHttpRequest = new XMLHttpRequest();
            }
            return xmlHttpRequest;
        },
        getFormData: function(name, file) {
            var args = arguments;
            var formData = new FormData();
            formData.append(name, file, file.name);

            for(var i = 2; i < args.length; i++) {
                this.append(formData, args[i]);
            }
            return formData;
        },
        append: function(formData, data) {
            if(formData == null || data == null) {
                return;
            }

            for(var i in data) {
                var value = data[i];
                var type = typeof(data[i]);

                if(type == "string" || type == "number" || type == "boolean") {
                    formData.append(i, value);
                }
                else if(className == "object" && value.length != null) {
                    for(var j = 0; j < value.length; j++) {
                        if(value[j] != null) {
                            formData.append(i, value[j]);
                        }
                    }
                }
                else {
                    formData.append(i, value);
                }
            }
        },
        getBlob: function(file, start, end) {
            var blob = file;
            start = (start || 0);
            end = (end || 0);

            if(file.slice) {
                console.log("file.slice: " + start + "/" + end);
                blob = file.slice(start, end);
                blob.name = file.name;
                blob.contentType = file.type;
            }

            if(file.webkitSlice) {
                console.log("file.webkitSlice " + start + "/" + end);
                blob = file.webkitSlice(start, end);
                blob.name = file.name;
                blob.contentType = file.type;
            }

            if(file.mozSlice) {
                console.log("file.mozSlice " + start + "/" + end);
                blob = file.mozSlice(start, end);
                blob.name = file.name;
                blob.contentType = file.type;
            }
            return blob;
        },
        getResponse: function(content, dataType) {
            try {
                if(dataType == "text") {
                    return content;
                }

                if(dataType == "script") {
                    var e = document.createElement("script");
                    e.type = "text/javascript";
                    e.text = content;
                    document.body.appendChild(e);
                    return content;
                }

                if(dataType == "json") {
                    return eval("(" + content + ")");
                }
                else {
                    /**
                     * text, html, etc..
                     */
                }
            }
            catch(e) {
            }
            return content;
        }
    };
})();
